import { useMemoizedFn } from 'ahooks';
import { BingMapsImageryProvider, BingMapsStyle, Cartesian3, ImageryLayer } from 'cesium';
import { isNil } from 'lodash';
import { useEffect } from 'react';
import { useCesium } from 'resium';
import { useAppSelector } from '../../../../store';

export default function Demo() {
    const { viewer } = useCesium();
    const pos = useAppSelector((state) => state.scene.initPosition);

    const clearImageryLayers = useMemoizedFn(() => {
        if (isNil(viewer)) return;
        if (viewer.imageryLayers.get(0)) {
            viewer.imageryLayers.remove(viewer.imageryLayers.get(0));
            clearImageryLayers();
        } else {
            return;
        }
    });

    useEffect(() => {
        if (isNil(viewer)) return;
        clearImageryLayers();

        const url = 'https://dev.virtualearth.net';
        const key = 'AmXdbd8UeUJtaRSn7yVwyXgQlBBUqliLbHpgn2c76DfuHwAXfRrgS5qwfHU6Rhm8';
        const layer = ImageryLayer.fromProviderAsync(
            BingMapsImageryProvider.fromUrl(url, {
                mapStyle: BingMapsStyle.AERIAL,
                key,
            }),
            {}
        );

        viewer.imageryLayers.add(layer);

        const target = Cartesian3.fromDegrees(pos.longitude, pos.latitude, 10000000);
        viewer.camera.setView({
            destination: target,
        });
    }, [clearImageryLayers, pos, viewer]);

    return null;
}
